package com.flyduck.common.exception;

import com.flyduck.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @program: vueshop
 * @description:
 * @author: flyduck
 * @create: 2024-05-07 21:13
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BusinessException.class)
    public Result<Void> handler(BusinessException e){
        log.error("业务异常", e);
        return Result.fail(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(value = NoHandlerFoundException.class)
    public Result<Void> handler(NoHandlerFoundException e){
        log.error("未找到资源异常", e);
        return Result.fail("未找到资源");
    }

    @ExceptionHandler(value = BindException.class)
    public Result<Void> handler(BindException e){
        log.error("实体校验异常", e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return Result.fail(objectError.getDefaultMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    public Result<Void> handler(RuntimeException e){
        log.error("系统异常", e);
        return Result.fail(e.getMessage());
    }
}
